package com.wqc.listener;

import com.wqc.common.constant.CommonConstants;
import com.wqc.model.Dictionary;
import com.wqc.service.DictionaryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ApplicationDataInit implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationDataInit.class);

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        // 获取spring 上下文
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();

        List<Dictionary> allDictionary = dictionaryService.getAllDictionary();

        for (Dictionary dictionary : allDictionary) {

            redisTemplate.opsForHash().put(CommonConstants.DICT_TYPEANDKEY + dictionary.getTypeandkey(),dictionary.getLangtype(),dictionary);

            redisTemplate.opsForSet().add(CommonConstants.DICT_TYPE + dictionary.getDictype() + ":" +dictionary.getLangtype(), dictionary);

        }

        LOGGER.info("init data end ...");

    }

}
